package com.minsu.controller;

import com.minsu.dto.LoginRequest;
import com.minsu.dto.LoginResponse;
import com.minsu.service.AuthService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @GetMapping("/login")
    public String loginPage(@RequestParam(required = false) String error,
                          @RequestParam(required = false) String logout,
                          Model model) {
        if (error != null) {
            model.addAttribute("error", "用户名或密码错误");
        }
        if (logout != null) {
            model.addAttribute("message", "您已成功退出系统");
        }
        model.addAttribute("loginRequest", new LoginRequest());
        return "login";
    }

    @PostMapping("/api/login")
    @ResponseBody
    public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest,
                                             BindingResult bindingResult) {
        // 参数验证
        if (bindingResult.hasErrors()) {
            String message = bindingResult.getFieldError().getDefaultMessage();
            return ResponseEntity.badRequest()
                    .body(LoginResponse.error(message));
        }

        try {
            LoginResponse response = authService.login(loginRequest);
            if (response.isSuccess()) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest()
                        .body(response);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(LoginResponse.error("登录失败：" + e.getMessage()));
        }
    }

    @GetMapping("/api/current-user")
    @ResponseBody
    public ResponseEntity<?> getCurrentUser() {
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null && auth.isAuthenticated()) {
                return ResponseEntity.ok(authService.getCurrentUser());
            }
            return ResponseEntity.badRequest().body("未登录");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取用户信息失败：" + e.getMessage());
        }
    }

    @PostMapping("/api/logout")
    @ResponseBody
    public ResponseEntity<?> logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                new SecurityContextLogoutHandler().logout(request, response, auth);
                return ResponseEntity.ok().body("退出成功");
            }
            return ResponseEntity.badRequest().body("未登录");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("退出失败：" + e.getMessage());
        }
    }
} 